#include "citycodeuitls.h"

#include <qdebug.h>
#include <qfile.h>
#include <qjsonarray.h>
#include <qjsondocument.h>
#include <qjsonobject.h>

CityCodeUitls::CityCodeUitls()
{

}

QString CityCodeUitls::getCityCodeFromName(QString cityName)
{
    if(cityMap.isEmpty()){
        initCityMap();
    }
    QMap<QString, QString>::iterator it = cityMap.find(cityName);
    if(it==cityMap.end()){
        it= cityMap.find(cityName+"市");
        if(it==cityMap.end()){
            it= cityMap.find(cityName+"县");
        }
        if(it==cityMap.end()){
            it= cityMap.find(cityName+"区");
        }
        if(it==cityMap.end()){
            return "";
        }
    }
    return  it.value();
}


void CityCodeUitls::initCityMap(){

    QFile file(":/citycode.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData=file.readAll();
    file.close();
    QJsonDocument jsonDoc=QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull() && jsonDoc.isArray()){
        QJsonArray cityArray=jsonDoc.array();
        for(QJsonValue val: cityArray){
            if (val.type()== QJsonValue::Object) {
                QString cityName=val["city_name"].toString();
                QString cityCode=val["city_code"].toString();
                cityMap.insert(cityName,cityCode);
            }

        }
    }
}
